package com.zsk.shop.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.utils.EntityConvertUtils;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.DeliveryAddress;
import com.zsk.shop.mapper.DeliveryAddressMapper;
import com.zsk.shop.model.params.DeliveryAddressParams;
import com.zsk.shop.model.results.DeliveryAddressResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Ys
 * @date 2021年10月26日 14:37
 */
@Service
@Slf4j
public class DeliveryAddressService extends ServiceImpl<DeliveryAddressMapper, DeliveryAddress> {

    public BaseResponse<DeliveryAddressResult> getDeliveryAddressList() {
        return BaseResponse.success(this.baseMapper.getDeliveryAddressList(HttpContext.getUserNo()));
    }

    public BaseResponse saveOrEditAddress(DeliveryAddressParams params) {
        DeliveryAddress deliveryAddress = EntityConvertUtils.convertAToB(params, DeliveryAddress.class);
        deliveryAddress.setRegion(deliveryAddress.getProvince() + deliveryAddress.getCity() + deliveryAddress.getArea());
        deliveryAddress.setUserNo(HttpContext.getUserNo());
        if (ToolUtil.isEmpty(params.getId())) {
            try {
                if (deliveryAddress.getIsChecked()) {
                    this.baseMapper.updateChecked(deliveryAddress.getUserNo());
                }
                deliveryAddress.setCreateTime(new Date());
                this.baseMapper.insertSelective(deliveryAddress);
            } catch (Exception e) {
                log.error(e.getMessage());
                return BaseResponse.error("添加失败，请重试...");
            }
        } else {
            try {
                if (deliveryAddress.getIsChecked()) {
                    this.baseMapper.updateChecked(deliveryAddress.getUserNo());
                }
                this.baseMapper.updateByPrimaryKeySelective(deliveryAddress);
            } catch (Exception e) {
                log.error(e.getMessage());
                return BaseResponse.error("编辑失败，请重试...");
            }
        }
        return BaseResponse.success();
    }

    public BaseResponse deleteDeliveryAddress(Long id) {
        this.baseMapper.deleteByPrimaryKey(id);
        return BaseResponse.success();
    }
}
